package com.sxj.PDMS.controller.admin;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.exception.ThrowUtils;
import com.sxj.PDMS.model.dto.admin.DataInformationListUpdateRequest;
import com.sxj.PDMS.model.dto.admin.DataInformationRequest;
import com.sxj.PDMS.model.dto.admin.DataInformationUploadRequest;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.model.entity.DataInformationList;
import com.sxj.PDMS.service.DataInformationListService;
import io.swagger.annotations.ApiOperation;
import com.sxj.PDMS.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import static com.sxj.PDMS.utils.VerifyUtil.formatDate;


@CrossOrigin
@RestController
@RequestMapping("/admin/resource")
@Slf4j
public class AdminResourceController {
    @Autowired
    private DataInformationListService dataInformationListService;

    @PostMapping("/upload_resource")
    public BaseResponse resourceUpload(@RequestBody DataInformationUploadRequest dataInformationUploadRequest) throws IOException, ParseException {
//        log.info("文件上传：name:{},type:{}",);
        log.info("资料上传：{}", dataInformationUploadRequest);
        if (dataInformationUploadRequest.getDataType() == null && dataInformationUploadRequest.getDataName() == null
                && dataInformationUploadRequest.getAddEvent() == null && dataInformationUploadRequest.getDataContent() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 文件大小进行限制50mb
        Boolean saved = dataInformationListService.resourceUpload(dataInformationUploadRequest);
        if (!saved) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        return Result.success();
    }

    @PostMapping("/upload_resourceFile")
    public String uploadResourceFile(@RequestPart(value = "uploadFile", required = false) MultipartFile uploadFile) {
        log.info("文件上传：{}", uploadFile);

        if (uploadFile != null && !uploadFile.isEmpty()) {
            synchronized (AdminResourceController.class) {
                //获取当前时间戳
                String flag = System.currentTimeMillis() + "";
                //获取文件名
                String fileName = uploadFile.getOriginalFilename();
                try {
                    //todo：/管理员提交resource的存放路径
                    String path = "D:\\user\\Desktop\\store\\resource\\";
                    FileUtil.writeBytes(uploadFile.getBytes(), path + "\\" + flag + "-" + fileName);
                    System.out.println(fileName + "上传成功");
                    Thread.sleep(1L);
                } catch (Exception e) {
                    System.out.println(fileName + "上传失败");
                }
                return flag;
            }
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件为空");
        }
    }


    @PutMapping("/modify_resource")
    public BaseResponse<Boolean> updateResource(@RequestBody DataInformationListUpdateRequest dataInformationListUpdateRequest,
                                                HttpServletRequest request) throws IOException, ParseException {
        String path = "D:\\user\\Desktop\\store\\resource\\";
        if (StringUtils.isAnyBlank(dataInformationListUpdateRequest.getAddEvent(), dataInformationListUpdateRequest.getDataName(),
                dataInformationListUpdateRequest.getNewDataContent(), dataInformationListUpdateRequest.getOldDataContent())
                && dataInformationListUpdateRequest.getDataNumber() == null && dataInformationListUpdateRequest.getDataType() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DataInformationList dataInformationList = new DataInformationList();
        dataInformationList.setAddEvent(dataInformationListUpdateRequest.getAddEvent());
        dataInformationList.setDataName(dataInformationListUpdateRequest.getDataName());
        dataInformationList.setDataType(dataInformationListUpdateRequest.getDataType());
        dataInformationList.setDataNumber(dataInformationListUpdateRequest.getDataNumber());
        dataInformationList.setDataContent(dataInformationListUpdateRequest.getNewDataContent());
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        dataInformationList.setTime(formatDate(currentTime));
        //删除旧文件
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(dataInformationListUpdateRequest.getOldDataContent())).findAny().orElse("");
        if (StrUtil.isNotEmpty(avatar)) {
            boolean isDeleted = FileUtil.del(path + avatar);
            if (isDeleted) {
                log.info("文件 {} 删除成功。", avatar);
            } else {
                log.error("文件 {} 删除失败。", avatar);
            }
        } else {
            log.warn("文件 {} 不存在，无需删除。", avatar);
        }

        // 更新消息
        boolean result = dataInformationListService.updateById(dataInformationList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // todo 记录修改日志
//        log.info("{}:{}修改{}资料文件", new Date().now(), request.getSession().getAttribute("userId"), dataInformationListUpdateRequest.getDataName());

        return Result.success(true);
    }

    @DeleteMapping("/delete_resource")
    public BaseResponse<Boolean> deleteResource(Long dataNumber) {
        //todo : 信息列表文件提交位置
        String path = "D:\\user\\Desktop\\store\\resource\\";
        if (dataNumber == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //删除文件
        DataInformationList dataInformationList = dataInformationListService.getById(dataNumber);
        if (dataInformationList == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号所指数据不存在");
        }
        boolean removed = dataInformationListService.removeById(dataNumber);
        if (!removed) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        String flag = dataInformationList.getDataContent();
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        if (StrUtil.isNotEmpty(avatar)) {
            boolean isDeleted = FileUtil.del(path + avatar);
            if (isDeleted) {
                log.info("文件 {} 删除成功。", avatar);
            } else {
                log.error("文件 {} 删除失败。", avatar);
            }
        } else {
            log.warn("文件 {} 不存在，无需删除。", avatar);
        }
        return Result.success(true);
    }

    @GetMapping("/selectAll_resource")
    public BaseResponse<PagingQueryResponse<DataInformationList>> selectResource(@RequestParam(defaultValue = "1") Integer page,
                                                                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<DataInformationList> pagingQueryResponse = dataInformationListService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }

    @GetMapping("/select_resource")
    public BaseResponse<PagingQueryResponse<DataInformationList>> selectWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                      DataInformationRequest dataInformationRequest) {

        PagingQueryResponse<DataInformationList> pagingQueryResponse = dataInformationListService.dataInformationListSelect(page, pageSize, dataInformationRequest);

        return Result.success(pagingQueryResponse);
    }

    @ApiOperation(value = "downloadResource", produces = "application/octet-stream")
    @GetMapping("/download_resource")
    public void downloadResource(HttpServletResponse response,
                                 @RequestParam("dataContent") String downloadFile) throws Exception {
        log.info("下载文件：{}", downloadFile);

        QueryWrapper<DataInformationList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_content", downloadFile);
        DataInformationList dataInformationList = dataInformationListService.getOne(queryWrapper);
        if (dataInformationList == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库中没有该文件");
        }
        log.info("下载文件：{}", downloadFile);
        // TODO: resource存放位置
        String path = "D:\\user\\Desktop\\store\\resource\\";
        OutputStream outPutStream;
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(downloadFile)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                byte[] bytes = FileUtil.readBytes(path + "\\" + avatar);
                outPutStream = response.getOutputStream();
                outPutStream.write(bytes);
                outPutStream.flush();
                outPutStream.close();
            }
        } catch (Exception e) {
            System.out.println(avatar + "下载失败");
        }
    }
}
